package com.hzw.saas.common.util;

import java.util.Arrays;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * @author zzl
 * @since 03/11/2021
 */
public class SpringELUtils {

    private static final SpelExpressionParser spelParser = new SpelExpressionParser();

    /**
     * 解析AOP中的EL表达式
     *
     * @param joinPoint 切入点
     * @param spel      SPEL表达式
     * @param clazz     EL表达式返回值类型
     * @param <T>       EL表达式返回值类型
     * @return EL表达式返回值
     */
    public static <T> T getSpelValue(JoinPoint joinPoint, String spel, Class<T> clazz) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        List<String> paramNameList = Arrays.asList(methodSignature.getParameterNames());
        List<Object> paramList = Arrays.asList(joinPoint.getArgs());
        EvaluationContext ctx = new StandardEvaluationContext();
        for (int i = 0; i < paramNameList.size(); i++) {
            ctx.setVariable(paramNameList.get(i), paramList.get(i));
        }
        Object value = spelParser.parseExpression(spel).getValue(ctx);
        return clazz.cast(value);
    }

}
